import 'dart:convert';
import 'package:report_sdk/src/models/event.dart';
import 'package:report_sdk/src/reporter/reporter.dart' as impl;
import 'package:report_sdk/src/config/report_sdk_config.dart';
import 'package:http/http.dart' as http;

class Reporter implements impl.Reporter {
  final ReportSdkConfig config;
  late final http.Client _httpClient;
  // 私有构造函数
  Reporter({required this.config}) {
    _httpClient = http.Client();
  }

  @override
  Future<bool> sendBatch(List<Event> events) async {
    try {
      final response = await _httpClient.post(
        Uri.parse(config.serverUrl),
        headers: {"Content-Type": "application/json", ...config.headers},
        body: jsonEncode({
          "user_id": config.userId,
          "timestamp_micros": config.now().microsecondsSinceEpoch.toString(),
          "events": events.map((event) => event.toJson()).toList(),
        }),
      );

      return response.statusCode == 200;
    } catch (e) {
      return false;
    }
  }

  @override
  void dispose() {
    _httpClient.close();
  }
}
